/**
 * sys role manager js
 * @constructor
 */
var Role = function () {
    var id;
    var name;
    var des;
    var roletype;
    var status;
    var iconcls;
    var seq;
}

var role;
var statusSwitchery;
$(document).ready(function () {

    var statusCheckbox = document.getElementById('status');
    statusSwitchery = new Switchery(statusCheckbox);

    // BOOTSTRAP TABLES USING FONT AWESOME ICONS
    // =================================================================
    // Require Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    //
    // =================================================================
    jQuery.fn.bootstrapTable.defaults.icons = {
        paginationSwitchDown: 'demo-pli-arrow-down',
        paginationSwitchUp: 'demo-pli-arrow-up',
        refresh: 'demo-pli-repeat-2',
        toggle: 'demo-pli-layout-grid',
        columns: 'demo-pli-check',
        detailOpen: 'demo-psi-add',
        detailClose: 'demo-psi-remove'
    }

    // EDITABLE - COMBINATION WITH X-EDITABLE
    // =================================================================
    // Require X-editable
    // http://vitalets.github.io/x-editable/
    //
    // Require Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    //
    // Require X-editable Extension of Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    // =================================================================
    $('#demo-editable').bootstrapTable({
        idField: 'id',
        uniqueId: 'id',
        sortable: true,
        sortOrder: "desc",
        pagination: true,//是否显示分页（*）
        queryParamsType: '', //默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort
                             // 设置为 ''  在这种情况下传给服务器的参数为：pageSize,pageNumber
        sidePagination: "server",   //分页方式：client客户端分页，server服务端分页（*）
        url: '/system/role/getRoleList',
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            /*formatter:'invoiceFormatter',*/
            title: 'ID',
            align: 'center',
            sortable: true
        }, {
            field: 'name',
            title: '角色名称',
            align: 'center',
            editable: {
                type: 'text',
                url: '/system/role/editName',
                validate: function (value) {
                    if (!$.trim(value)) {
                        return '角色名称不能为空';
                    }
                    var valid;
                    $.ajax({
                        url: '/system/role/checkName',
                        type: 'post',
                        async: false,
                        data: {"name": value},
                        success: function (result) {
                            valid = result.valid;
                        }
                    })
                    if (!valid) {
                        return '角色名称已被占用';
                    }

                }
            },
            sortable: true
            /*}, {
                field: 'avatar',
                title: '头像',
                formatter:'avatarFormatter',
            }, {
                field: 'roletype',
                title: '角色类型',
                align: 'center',
                formatter:'RoleTypeFormatter',
                sortable:true */
        }, {
            field: 'status',
            align: 'center',
            title: '状态',
            formatter: formatter.roleStatusFormatter,
            sortable: true
        }, {
            field: 'des',
            title: '角色简介',
            align: 'center',
            editable: {
                type: 'text',
                url: '/system/role/editDes',
            }
        }, {
            field: 'iconcls',
            title: 'ICON',
            align: 'center',
            formatter: formatter.roleIconFormatter,
            /* editable: {
                 type: 'text',
                 url: '/system/role/editIcon',
             }*/
        }, {
            field: 'seq',
            title: '序号',
            align: 'center',
            sortable: true
        }, {
            field: '',
            title: '操作',
            align: 'center',
            formatter: formatter.roleEditFormatter,
        }]
    });


    // X-EDITABLE USING FONT AWESOME ICONS
    // =================================================================
    // Require X-editable
    // http://vitalets.github.io/x-editable/
    //
    // Require Font Awesome
    // http://fortawesome.github.io/Font-Awesome/icons/
    // =================================================================
    $.fn.editableform.buttons =
        '<button type="submit" class="btn btn-primary editable-submit">' +
        '<i class="fa fa-fw fa-check"></i>' +
        '</button>' +
        '<button type="button" class="btn btn-default editable-cancel">' +
        '<i class="fa fa-fw fa-times"></i>' +
        '</button>';

    // BOOTSTRAP TABLE - CUSTOM TOOLBAR
    // =================================================================
    // Require Bootstrap Table
    // http://bootstrap-table.wenzhixin.net.cn/
    // =================================================================
    var $table = $('#demo-editable'), $remove = $('#demo-delete-row'), $add = $('#demo-add-row'), $save = $('#save');

    $table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
    });
    //删除
    $remove.click(function () {
        var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
        });
        $.ajax({
            url: "/system/role/delete?ids=" + ids,
            success: function (result) {
                var idsArr = result.split(",");
                var a = [];
                for (var i in idsArr) {
                    a.push(parseInt(idsArr[i]))
                }
                $table.bootstrapTable('remove', {
                    field: 'id',
                    values: a
                });
            },
            error: function (result) {
                bootbox.alert({
                    closeButton: false,
                    message: result.responseJSON.msg,
                });
            }
        });
        $remove.prop('disabled', true);
    });

    $add.click(function () {
        setValueNull();
        $("#demo-default-modal").modal('show');
    });

    $save.click(function () {
        addOrUpdate();
    });


});

// set modal value null
function setValueNull() {

    $("#id").val(null);
    $("#name").val(null);
    $("#des").val(null);
    $("#iconcls").val(null);

    SwitcheryUtils.setEnable(statusSwitchery, true)

}

//sync role value
function syncRole() {
    if (role == undefined) {
        role = new Role();
    }
    role.id = $("#id").val();
    role.name = $("#name").val();
    role.des = $("#des").val();
    role.iconcls = $("#iconcls").val();
    role.status = document.getElementById('status').checked ? 0 : 1;
}

//set role value to modal
function setRoleValue(role) {

    $("#id").val(role.id);
    $("#name").val(role.name);
    $("#des").val(role.des);
    $("#iconcls").val(role.iconcls);

    if (role.status == 0) {
        SwitcheryUtils.setEnable(statusSwitchery, true)
    } else {
        SwitcheryUtils.setEnable(statusSwitchery, false)
    }
}

//edit role
function edit(id) {
    var data = $('#demo-editable').bootstrapTable('getRowByUniqueId', id);
    setRoleValue(data);
    $("#demo-default-modal").modal('show');
}

function enable(id, status) {
    if(status == 1){
        status = 0;
    }else{
        status = 1;
    }
    $.ajax({
        url: "/system/role/addOrUpdate",
        type: 'post',
        dataType: "json",
        data: {
            id: id,
            status: status
        },
        success: function (result) {
            bootbox.alert({
                closeButton: false,
                message: result.msg,
                callback: function (result) {
                    //Callback function here
                    window.location.reload();
                },
                animateIn: 'flipInX',
                animateOut: 'flipOutX'
            });
        },
        error: function (result) {
            bootbox.alert({
                closeButton: false,
                message: result.responseJSON.msg,
            });
        }
    });
}

//addOrUpdate
function addOrUpdate() {

    syncRole();

    $("#demo-default-modal").modal('hide');
    $.ajax({
        url: "/system/role/addOrUpdate",
        type: 'post',
        dataType: "json",
        data: role,
        success: function (result) {
            bootbox.alert({
                closeButton: false,
                message: result.msg,
                callback: function (result) {
                    //Callback function here
                    window.location.reload();
                },
                animateIn: 'flipInX',
                animateOut: 'flipOutX'
            });
        },
        error: function (result) {
            bootbox.alert({
                closeButton: false,
                message: result.responseJSON.msg,
            });
        }
    });
}
